<template>
  <div class="app-container">
    <el-page-header
      content="接口测试 - 报告详情"
      style="margin-bottom: 20px"
      @back="goBack"
    />
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header><strong> 报告信息 </strong></template>
          <el-form
            label-position="left"
            label-width="100px"
            style="margin-left: 20px; word-break: break-all; width: 100%; height: 300px"
            :model="resultData"
          >
            <el-form-item label="结果id：" style="margin: 10px 0;">
              <span>{{ resultData.id }}</span>
            </el-form-item>
            <el-form-item label="测试套件：" style="margin: 10px 0;">
              <span>「{{ resultData.suiteId }}」{{ resultData.suiteName }}</span>
            </el-form-item>
            <el-form-item label="执行用户：" style="margin: 10px 0;">
              <span>{{ resultData.runUser }}</span>
            </el-form-item>
            <el-form-item label="运行状态：" style="margin: 10px 0;">
              <el-tag style="margin-left: 0px" size="small" :type="getRunStatusName(resultData.status)==='通过'?'success':getRunStatusName(resultData.status)==='警告'?'warning':getRunStatusName(resultData.status) === '失败'? 'danger' : 'info'">
                <i v-if="getRunStatusName(resultData.status) === '运行中'" class="el-icon-loading" style="margin-right: 5px;" />
                {{ getRunStatusName(resultData.status) }}
              </el-tag>
              <el-checkbox v-if="getRunStatusName(resultData.status) !== '通过'" v-model="onlyShowFailed" style="margin-left: 10px;">只显示未通过的结果</el-checkbox>
            </el-form-item>
            <el-form-item label="创建时间：" style="margin: 10px 0;">
              <span>{{ resultData.createdAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
            <el-form-item label="结束时间：" style="margin: 10px 0;">
              <span>{{ resultData.endAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
            <el-form-item label="总耗时：" style="margin: 10px 0;">
              <span>{{ resultData.totalTime }}</span>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div ref="chart" style="width: 100%;height: 365px;" />
        </el-card>
      </el-col>
    </el-row>
    <el-divider><span style="color: #909399;"> 运行信息 </span></el-divider>
    <el-card shadow="hover">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item
          v-for="item in resultData.cidList"
          v-show="!onlyShowFailed || item.status !== 4"
          :key="item.id"
          style="position: relative"
          @click.native="handleClick(item.cid)"
        >
          <template #title>
            测试用例：
            <strong style="color: #606266">
              「
              <a
                :href="`/#/interface_test/test_case?id=${item.cid}`"
                target="_blank"
                style="color: #409eff"
              >
                {{ item.cid }}
              </a>
              」
              {{ item.cidName }}
            </strong>
            <el-tag style="margin-left: 15px" size="small" :type="getRunStatusElTagType(item.status)">
              <i v-if="getRunStatusName(item.status) === '运行中'" class="el-icon-loading" style="margin-right: 5px;" />
              {{ getRunStatusName(item.status) }}
            </el-tag>
          </template>
          <el-tabs tab-position="left" type="border-card">
            <el-tab-pane v-for="(d, k) in stepDetail" :key="k">
              <template #label>
                <div class="flex-center">
                  {{ k }}
                  <el-tag :type="getRunStatusElTagType(d.status)" size="small" style="margin-left: 5px">
                    <i v-if="getRunStatusName(d.status) === '运行中'" class="el-icon-loading" style="margin-right: 5px;" />
                    {{ getRunStatusName(d.status) }}
                  </el-tag>
                </div>
              </template>
              <div style="text-align: right">
                追踪 ID: resultId-{{ resultData.id }}-caseId-{{ item.cid }}-ic-{{ k }}
                <el-tooltip :open-delay="500" placement="top">
                  <div slot="content">为了便于日志排查，在 Http 请求的 Head 中都添加了此 ID<br>例如: x-qap-request-id: resultId-3744-caseId-8189-ic-1-1;</div>
                  <i class="el-icon-question" style="font-size: 15px; font-weight: 500; color:#409eff" />
                </el-tooltip>
              </div>
              <el-table :data="d.testResultSteps " border style="width: 100%">
                <el-table-column align="center" label="状态" width="70px">
                  <template v-slot="scope">
                    <i v-if="scope.row.status <= 3" class="el-icon-success" style="color: #67c23a" />
                    <i v-if="scope.row.status === 4" class="el-icon-info" style="color: #409eff" />
                    <i v-if="scope.row.status >= 5 && scope.row.status <= 11" class="el-icon-warning" style="color: #e6a23c" />
                    <i v-if="scope.row.status >= 12" class="el-icon-error" style="color: #f56c6c" />
                  </template>
                </el-table-column>
                <el-table-column label="Agent" width="180px">
                  <template>{{ item.agentName }}</template>
                </el-table-column>
                <el-table-column label="详情">
                  <template v-slot="scope">
                    <el-tag v-show="scope.row.desc" style="margin-right: 5px;" type="info">{{ scope.row.desc }}</el-tag>
                    <el-tag v-show="scope.row.type" style="margin-right: 5px;">{{ scope.row.type }}</el-tag>
                    <span v-html="$options.filters.translateHtml($options.filters.textareaFormat($options.filters.html2Escape(scope.row.log)))" />
                  </template>
                </el-table-column>
                <el-table-column label="运行时间" width="80">
                  <template v-slot="scope">
                    <span>{{ scope.row.createdAt | parseTime('{h}:{i}:{s}') }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getResultInfoById as get_result_info, getCaseResultDetails as get_case_details } from '@/api/functional_test/automated_test/test_result'
import { getRunStatusName, getRunStatusElTagType, getRunStatusColor } from '@/enum/runStatus.js'
import { updateCurrentCompanyProject } from '@/api/user'

export default {
  filters: {
    // 转义html标签，会将 & 转为 &amp; < 转为 &lt; > 转为 &gt;
    html2Escape(text) {
      return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
    },
    // 将 \n 和 \r\n 转为 <br/>
    textareaFormat: function(text) {
      return text.replace(/\n|\r\n/g, '<br/>')
    },
    // 将 http 或 https 转为 <a> 标签
    translateHtml: function(msg) {
      return msg.replace(
        /((http|https|ftp|file):\/\/[-A-Za-z0-9+&@#()/%?=~_|!:,.\\;]+[-A-Za-z0-9+&@#()/%=~_\\|])/g,
        `<a style='color:#2660f5;text-decoration:underline;cursor:hand;' href="$1" target="_blank">$1</a>`
      )
    }
  },
  data() {
    const option = {
      title: {
        text: '用例运行状态分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'right'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '50%',
          data: this.echartsData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(10, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    return {
      activeName: '0',
      stepActiveName: '',
      chart: null,
      myChart: null,
      option,
      resultID: this.$route.query.resultId,
      type: this.$route.query.type,
      resultData: {},
      stepDetail: [],
      echartsData: [],
      dataMap: [],
      caseList: [],
      isOpen: false,
      onlyShowFailed: false
    }
  },
  watch: {
    echartsData(newVal) {
      this.chart.setOption({
        series: [{
          data: newVal
        }]
      })
    },
    activeName(newVal) {
      if (newVal) {
        this.isOpen = true
      } else {
        this.isOpen = false
      }
    }
  },
  mounted() {
    this.initChart()
    this.get_result_info()

    // 如果 url 中的 projectId 跟 store 中的 projectId 不同，则切换到 url 中的项目
    if (this.$route.query.companyId && this.$route.query.projectId && (Number(this.$route.query.companyId) !== this.$store.getters.companyId || Number(this.$route.query.projectId) !== this.$store.getters.projectId)) {
      const tmp = {
        companyId: this.$route.query.companyId,
        projectId: this.$route.query.projectId
      }
      updateCurrentCompanyProject(tmp).then(response => {
        // 调用后台接口，更新用户当前 产品-项目 成功后，修改 前端store 中的 companyId、projectId
        this.$store.dispatch('user/updateCompanyIdProjectId', tmp).then(() => {
        })
      })
    }
  },
  created() {
  },
  beforeDestroy() {
    this.chart.dispose()
  },
  methods: {
    getRunStatusName,
    getRunStatusElTagType,
    handleClick(cid) {
      if (this.isOpen) {
        this.get_case_details(cid, this.resultID, this.type)
        this.isOpen = false
      }
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption(this.option)
    },
    get_result_info: function() {
      get_result_info(this.$store.getters.projectId, this.resultID, this.type).then(response => {
        this.resultData = response.data
        this.caseList = response.data.cidList
        this.caseList.forEach(item => {
          this.dataMap.push(item.status)
        })
        const arrTmp = []
        this.dataMap.forEach((val) => {
          if (arrTmp.indexOf(val) === -1) {
            this.echartsData.push({
              name: this.getRunStatusName(val),
              value: this.dataMap.filter(v => v === val).length,
              itemStyle: { 'color': getRunStatusColor(val) }
            })
            arrTmp.push(val)
          }
        })
      })
    },
    get_case_details(cid, rid) {
      get_case_details(cid, rid).then(response => {
        this.stepDetail = response.data
      })
    },
    goBack() {
      this.$router.back()
    }
  }
}
</script>
